﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Dapper;
using LibMS.Models;
using System.Web;
using System.IO;
using System.Threading.Tasks;
using System.Net.Http.Headers;

namespace LibMS.Controllers
{
    [AllowAnonymous]
    public class ApiLibDocumentsController : ApiController
    {
        private readonly UnitOfWork _unitOfWork = new UnitOfWork();

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetData(int index, int size, string order)
        {
            int? total;
            string message;
            var parameters = new DynamicParameters();
            parameters.Add("@PageSize", size);
            parameters.Add("@PageIndex", index);
            parameters.Add("@OrderBy", order);
            var data = _unitOfWork.LibDocuments.GetData(out total, out message, parameters);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //Success
            var sqlResult = data as List<LibDocuments> ?? null;
            var result = new
            {
                success = true,
                message = string.Empty,
                total = total,
                data = sqlResult
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetById(int documentId)
        {
            string message;
            var parameters = new DynamicParameters();
            parameters.Add("@DocumentId", documentId);
            parameters.Add("@Current", dbType: System.Data.DbType.Int32, direction: System.Data.ParameterDirection.Output);
            var data = _unitOfWork.LibDocuments.GetById(out message, parameters);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //Success
            var result = new
            {
                success = true,
                message = string.Empty,
                currentDocument = parameters.Get<int>("@Current"),
                data = data
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetCurrentTotalInLib(int documentId)
        {
            string message;
            var parameters = new DynamicParameters();
            parameters.Add("@DocumentId", documentId);
            parameters.Add("@Current", dbType: System.Data.DbType.Int32, direction: System.Data.ParameterDirection.Output);
            var data = _unitOfWork.LibDocuments.QuerySpNT(out message, StringConstant.TABLE_LIBDOCUMENTS + StringConstant.SP_LIBDOCUMENTS_GETTOTALCURRENTDOCUMENT, parameters);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //Success
            var result = new
            {
                success = true,
                message = string.Empty,
                currentDocument = parameters.Get<int>("@Current"),
                data = data
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetByCategory(int categoryId)
        {
            int? total;
            string message;
            var parameters = new DynamicParameters();
            parameters.Add("@CategoryId", categoryId);
            parameters.Add("@PageSize", 1000);
            parameters.Add("@PageIndex", 1);
            parameters.Add("@OrderBy", "CreateDate");
            var data = _unitOfWork.LibDocuments.QuerySp(out total, out message, StringConstant.TABLE_LIBDOCUMENTS + StringConstant.SP_LIBDOCUMENTS_GETBYCATEGORYID, parameters);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //Success
            var sqlResult = data as List<LibDocuments> ?? null;
            var result = new
            {
                success = true,
                message = string.Empty,
                total = total,
                data = data
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetByCategoryNew(int categoryId, int index, int size, string order)
        {
            int? total;
            string message;
            var parameters = new DynamicParameters();
            parameters.Add("@CategoryId", categoryId);
            parameters.Add("@PageSize", size);
            parameters.Add("@PageIndex", index);
            parameters.Add("@OrderBy", order);
            var data = _unitOfWork.LibDocuments.QuerySp(out total, out message, StringConstant.TABLE_LIBDOCUMENTS + StringConstant.SP_LIBDOCUMENTS_GETBYCATEGORYID, parameters);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //Success
            var sqlResult = data as List<LibDocuments> ?? null;
            var result = new
            {
                success = true,
                message = string.Empty,
                total = total,
                data = data
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetTop5ByCategory(int categoryId)
        {
            string message;
            var parameters = new DynamicParameters();
            parameters.Add("@CategoryId", categoryId);
            var data = _unitOfWork.LibDocuments.QuerySpNT(out message, StringConstant.TABLE_LIBDOCUMENTS + StringConstant.SP_LIBDOCUMENTS_GETTOP5BYCATEGORYID, parameters);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //Success
            var sqlResult = data as List<LibDocuments> ?? null;
            var result = new
            {
                success = true,
                message = string.Empty,
                data = data
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetTop5New()
        {
            string message;
            var data = _unitOfWork.LibDocuments.QuerySpNT(out message, StringConstant.TABLE_LIBDOCUMENTS + StringConstant.SP_LIBDOCUMENTS_GETTOP5NEW);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //Success
            var sqlResult = data as List<LibDocuments> ?? null;
            var result = new
            {
                success = true,
                message = string.Empty,
                data = data
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetTop5View()
        {
            string message;
            var data = _unitOfWork.LibDocuments.QuerySpNT(out message, StringConstant.TABLE_LIBDOCUMENTS + StringConstant.SP_LIBDOCUMENTS_GETTOP5VIEW);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //Success
            var sqlResult = data as List<LibDocuments> ?? null;
            var result = new
            {
                success = true,
                message = string.Empty,
                data = data
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetByRack(int rackId)
        {
            int? total;
            string message;
            var parameters = new DynamicParameters();
            parameters.Add("@RackId", rackId);
            parameters.Add("@PageSize", 1000);
            parameters.Add("@PageIndex", 1);
            parameters.Add("@OrderBy", "CreateDate");
            var data = _unitOfWork.LibDocuments.QuerySp(out total, out message, StringConstant.TABLE_LIBDOCUMENTS + StringConstant.SP_LIBDOCUMENTS_GETBYRACKID, parameters);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //Success
            var sqlResult = data as List<LibDocuments> ?? null;
            var result = new
            {
                success = true,
                message = string.Empty,
                total = total,
                data = data
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetUploadData(int documentId, int index, int size, string order)
        {
            int? total;
            string message;
            var parameters = new DynamicParameters();
            parameters.Add("@DocumentId", documentId);
            parameters.Add("@PageSize", size);
            parameters.Add("@PageIndex", index);
            parameters.Add("@OrderBy", order);
            var data = _unitOfWork.LibUploadData.QuerySp(out total, out message, StringConstant.TABLE_LIBDOCUMENTS + StringConstant.SP_LIBDOCUMENTS_GETFILEUPLOAD, parameters);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //Success
            var sqlResult = data as List<LibUploadData> ?? null;
            var result = new
            {
                success = true,
                message = string.Empty,
                total = total,
                data = sqlResult
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage SearchBy1Condition(int index, int size, string search)
        {
            int? total;
            string message;
            var parameters = new DynamicParameters();
            parameters.Add("@PageSize", size);
            parameters.Add("@PageIndex", index);
            parameters.Add("@SearchCondition", search);
            var data = _unitOfWork.LibDocuments.QuerySp(out total, out message, StringConstant.TABLE_LIBDOCUMENTS + StringConstant.SP_LIBDOCUMENTS_SEARCHONECONDITION, parameters);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //Success
            var sqlResult = data as List<LibDocuments> ?? null;
            var result = new
            {
                success = true,
                message = string.Empty,
                total = total,
                data = sqlResult
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        [Authorize(Roles = "System Admin, Lib Admin")]
        [System.Web.Http.HttpPost]
        public Task<HttpResponseMessage> UploadThumbnail(string filename)
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            var provider = new CustomMultipartFormDataStreamProvider(System.Web.Hosting.HostingEnvironment.MapPath(System.Configuration.ConfigurationManager.AppSettings["ThumbnailFolder"]));
            var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                {
                    Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                }

                var fileName = provider.FileData.FirstOrDefault().LocalFileName;

                var result = new
                {
                    success = true,
                    message = fileName
                };
                return Request.CreateResponse(HttpStatusCode.OK, result);
            });

            return task;
        }

        [Authorize(Roles = "System Admin, Lib Admin")]
        [System.Web.Http.HttpPost]
        public HttpResponseMessage UpdateData(LibDocuments entity)
        {
            string message;
            var parameters = new DynamicParameters();
            parameters.Add("@DocumentId", entity.DocumentId);
            parameters.Add("@CategoryId", entity.CategoryId);
            parameters.Add("@RackId", entity.RackId);
            parameters.Add("@KyHieu", 0);
            parameters.Add("@DocumentName", entity.DocumentName);
            parameters.Add("@ThumbnaiPath", entity.ThumbnaiPath);
            parameters.Add("@NXB", entity.NXB);
            parameters.Add("@Author", entity.Author);
            parameters.Add("@Total", entity.Total);
            parameters.Add("@Descriptions", entity.Descriptions);
            var data = _unitOfWork.LibDocuments.Update(out message, parameters);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //Success
            var result = new
            {
                success = true,
                message = string.Empty,
                data = entity
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        [Authorize(Roles = "System Admin, Lib Admin")]
        [System.Web.Http.HttpPost]
        public HttpResponseMessage CreateData(LibDocuments entity)
        {
            string message;
            var parameters = new DynamicParameters();
            parameters.Add("@CategoryId", entity.CategoryId);
            parameters.Add("@RackId", entity.RackId);
            parameters.Add("@KyHieu", 0);
            parameters.Add("@DocumentName", entity.DocumentName);
            parameters.Add("@ThumbnaiPath", entity.ThumbnaiPath);
            parameters.Add("@NXB", entity.NXB);
            parameters.Add("@Author", entity.Author);
            parameters.Add("@Total", entity.Total);
            parameters.Add("@Descriptions", entity.Descriptions);
            parameters.Add("@CreateBy", User.Identity.Name);
            parameters.Add("@DocumentId", dbType: System.Data.DbType.Int32, direction: System.Data.ParameterDirection.Output);
            var data = _unitOfWork.LibDocuments.Create(out message, parameters);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            //Success
            entity.DocumentId = parameters.Get<int>("@DocumentId");
            var result = new
            {
                success = true,
                message = string.Empty,
                data = entity
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

        [Authorize(Roles = "System Admin, Lib Admin")]
        [System.Web.Http.HttpPost]
        public HttpResponseMessage DeleteData(int documentId)
        {
            //Get File uploaded
            int? total;
            string message;
            var parameters = new DynamicParameters();
            parameters.Add("@DocumentId", documentId);
            parameters.Add("@PageSize", 50);
            parameters.Add("@PageIndex", 1);
            var data = _unitOfWork.LibUploadData.QuerySp(out total, out message, StringConstant.TABLE_LIBDOCUMENTS + StringConstant.SP_LIBDOCUMENTS_GETFILEUPLOAD, parameters);
            if (data == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }

            //Delete file in DB
            string message1;
            var parameters1 = new DynamicParameters();
            parameters1.Add("@DocumentId", documentId);
            var data1 = _unitOfWork.LibDocuments.Delete(out message1, parameters1);
            if (data1 == null)//Query error
            {
                var error = new
                {
                    success = false,
                    message = message1
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }

            //Delete file in folder
            foreach (var item in data.ToList())
            {
                var filePath = System.Web.Hosting.HostingEnvironment.MapPath(System.Configuration.ConfigurationManager.AppSettings["BaseDataFolder"] + item.FileName);
                if (System.IO.File.Exists(filePath))
                {
                    try
                    {
                        System.IO.File.Delete(filePath);
                        //Delete thumbnail
                        var thumbPath = System.Web.Hosting.HostingEnvironment.MapPath(System.Configuration.ConfigurationManager.AppSettings["BaseDataFolder"] + "_thumbs/" + item.FileName + ".png");
                        if (System.IO.File.Exists(thumbPath))
                        {
                            System.IO.File.Delete(thumbPath);
                        }
                    }
                    catch (Exception)
                    {  }
                }
            }
            //Success
            var result = new
            {
                success = true,
                message = string.Empty,
                data = documentId
            };
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }
    }

    public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public CustomMultipartFormDataStreamProvider(string path)
            : base(path)
        {

        }

        public override string GetLocalFileName(HttpContentHeaders headers)
        {
            return Guid.NewGuid() + headers.ContentDisposition.FileName.Replace("\"", string.Empty);
        }
    }
}
